//
//  BequoteVC.m
//  Zhiche-Carriage
//
//  Created by 王亚陆 on 16/6/14.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "BequoteVC.h"
#import "Common.h"
#import "BequoteCell.h"
#import <Masonry.h>
#import "AcceptOrderVC.h"
#import "CustomTextField.h"
#import "ReceiveViewController.h"
@interface BequoteVC ()
{
    Common * com;
    UIView * nav;
    UITableView * table;
    NSMutableArray * dataSouceArr;
    NSMutableArray * priceArr;
    NSMutableDictionary * dicUrl;
    NSMutableDictionary * fees;
 
    NSMutableArray * DataArr;
}

@property (nonatomic,strong) UIView * backview;
@property (nonatomic,strong) UILabel * insuranceLabel;
@property (nonatomic,strong) UILabel * totalPrice;
@end

@implementation BequoteVC
- (instancetype)init

{
    self = [super init];
    if (self) {
        self.orderid = [[NSString alloc]init];
        self.recommendid = [[NSString alloc]init];
        
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    com = [[Common alloc]init];
    priceArr = [[NSMutableArray alloc]init];
    self.view.backgroundColor = GrayColor;
    DataArr = [[NSMutableArray alloc]init];
    
    dicUrl = [[NSMutableDictionary alloc]init];
    [dicUrl setObject:self.orderid forKey:@"orderid"];
    [dicUrl setObject:@"1" forKey:@"recommendid"];
    [dicUrl setObject:@"" forKey:@"fees"];
    fees = [[NSMutableDictionary alloc]init];
    
    nav = [self createNav:@"报价"];
    [self.view addSubview:nav];
    self.isTwo = YES;

//    [self createTable];
    [self createDate];
    
    [self createUI];
}

-(void)createUI{
    
    _backview = [[UIView alloc]init];
    _backview.backgroundColor = WhiteColor;
    [self.view addSubview:_backview];
    [_backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(nav.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 216*kHeight));
    }];

    NSArray * leftName = @[@"参考报价",@"参考价",@"报价",@"保险",@"合计运费"].mutableCopy;
    

    for (int i=0; i<5; i++) {
        
        UILabel * label = [com createUIlabel:leftName[i] andFont:FontOfSize14 andColor:LineGrayColor];
        if (i==0) {
            label.textColor = littleBlackColor;
        }
        [_backview addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_backview.mas_left).with.offset(19*kWidth);
            make.centerY.equalTo(nav.mas_bottom).with.offset(21.5*kHeight+43*kHeight*i);
        }];
        
        UIView * line = [[UIView alloc]init];
        line.backgroundColor = GrayColor;
        [_backview addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_backview.mas_left);
            make.top.equalTo(nav.mas_bottom).with.offset(43*kHeight*(i+1));
            make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
        }];
    }
    CustomTextField * field = [self createField:@"" andTag:999 andFont:FontOfSize14];
    field.placeholder = @"请输入价格";
    [field addTarget:self action:@selector(FieldWithText:) forControlEvents:UIControlEventEditingChanged];


    [_backview addSubview:field];
    [field mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_backview.mas_right).with.offset(-15*kWidth);
        make.centerY.mas_equalTo(nav.mas_bottom).with.offset(107.5*kHeight);
        make.size.mas_equalTo(CGSizeMake( 135*kWidth, 43*kHeight));
    }];
    
    
    
    UIButton * ShipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ShipBtn setTitle:@"确认报价" forState:UIControlStateNormal];
    [ShipBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [ShipBtn addTarget:self action:@selector(pressShipBtn) forControlEvents:UIControlEventTouchUpInside];
    ShipBtn.layer.cornerRadius = 5;
    ShipBtn.layer.borderWidth = 0.5;
    ShipBtn.layer.borderColor = YellowColor.CGColor;
    ShipBtn.backgroundColor = YellowColor;
    [self.view addSubview:ShipBtn];
    [ShipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_backview.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
        make.top.mas_equalTo(_backview.mas_bottom).with.offset(38*kHeight);
    }];
    
    _insuranceLabel = [com createUIlabel:@"" andFont:FontOfSize14 andColor:littleBlackColor];
    [_backview addSubview:_insuranceLabel];
    [_insuranceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nav.mas_bottom).with.offset(21.5*kHeight+43*kHeight*3);
        make.right.mas_equalTo(_backview.mas_right).with.offset(-15*kHeight);
    }];
    _totalPrice = [com createUIlabel:@"" andFont:FontOfSize14 andColor:littleBlackColor];
    [_backview addSubview:_totalPrice];
    [_totalPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nav.mas_bottom).with.offset(21.5*kHeight+43*kHeight*4);
        make.right.mas_equalTo(_backview.mas_right).with.offset(-15*kHeight);
    }];

}

-(void)FieldWithText:(CustomTextField*)field{
    
    [fees setObject:field.text forKey:@"money"];
    
}


-(void)viewWillAppear:(BOOL)animated{
    
//    feeinfo
    
    
    NSString * string = [NSString stringWithFormat:@"%@?id=%@",feeinfo_Url,self.orderid];
    
    [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj){
        

        NSLog(@"%@",responseObj);
        
        DataArr = responseObj[@"data"][@"fees"];
        _insuranceLabel.text = [NSString stringWithFormat:@"%@",DataArr[1][@"money"]];
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //        [hud dismiss:YES];
    });

    
    
}
-(void)createTable{
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 65*kHeight, Main_Width,Main_height/2) style:UITableViewStylePlain];
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    UIButton * ShipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ShipBtn setTitle:@"确认报价" forState:UIControlStateNormal];
    [ShipBtn setTitleColor:BlackColor forState:UIControlStateNormal];
    [ShipBtn addTarget:self action:@selector(pressShipBtn) forControlEvents:UIControlEventTouchUpInside];
    ShipBtn.layer.borderWidth = 1;
    ShipBtn.layer.borderColor = RGBACOLOR(149, 149, 149, 1).CGColor;
    ShipBtn.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:ShipBtn];
    [ShipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(table.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(Main_Width/3*2, 35*kHeight));
        make.top.mas_equalTo(table.mas_bottom).with.offset(30*kHeight);
    }];

}

-(void)pressShipBtn{
    
    //create_Url
    NSString * string = [NSString stringWithFormat:@"%@",create_Url];
    //orderid 订单id
    //recommendid 推荐id
    //fees 	json数组 	Y 		[{"feeName":"合计运费","cost":"1000.00"},{"feeName":"保险费","cost":"50.00"}...]

    NSString * feesID =[NSString stringWithFormat:@"%@",DataArr[1][@"id"]];
    [fees setObject:feesID forKey:@"id"];
    

//    for (int i =0; i<3; i++) {
//        NSMutableDictionary * feeName = [[NSMutableDictionary alloc]init];
//        [feeName setObject:priceArr[i] forKey:@"cost"];
//        [feeName setObject:dataSouceArr[i][@"feeType"] forKey:@"feeName"];
//
//        [fees addObject:feeName];
//    }
    NSMutableArray * feesArr = [NSMutableArray arrayWithObject:fees];
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:feesArr options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    [dicUrl setObject:jsonString forKey:@"fees"];
    
    
    
    
    [com afPostRequestWithUrlString:string parms:dicUrl finishedBlock:^(id responseObj) {
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dicObj);
        NSString * success = [NSString stringWithFormat:@"%@",dicObj[@"success"]];
        if ([success isEqualToString:@"1"]) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[ReceiveViewController class]]) {
                        [self.navigationController popToViewController:controller animated:YES];
                    }
                }
            });
        }else{
            [self createUIAlertController:[NSString stringWithFormat:@"%@",dicObj[@"message"]]];
        }
        
    } failedBlock:^(NSString *errorMsg) {
        
        
    }];
    
    
    
    
}



-(void)createDate{
    
    NSString * string = [NSString stringWithFormat:@"%@",feetype_list_Url];
    [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj){
        
        NSLog(@"%@",responseObj);
//        dataSouceArr = [NSMutableArray arrayWithObject:responseObj[@"data"]];
        dataSouceArr = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        
        for (int i =0; i<dataSouceArr.count; i++) {
            
            NSString * string = [NSString stringWithFormat:@"0"];
            [priceArr addObject:string];
        }
        
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:@"最终报价" forKey:@"feeType"];
        
        NSMutableArray * arr = [[NSMutableArray alloc]init];
        NSMutableDictionary * dic1 = [[NSMutableDictionary alloc]init];
        [dic1 setObject:@"" forKey:@"feeType"];
        [arr addObject:dic1];
        [dic setObject:arr forKey:@"list"];
        
        [dataSouceArr addObject:dic];
        [table reloadData];
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37*kHeight;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *str=@"str";
    
    BequoteCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[BequoteCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    
    if (indexPath.section == dataSouceArr.count-1) {
        cell.field.hidden = YES;
        cell.price.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title.text = dataSouceArr[indexPath.section][@"list"][0][@"feeType"];
    cell.field.backgroundColor = [UIColor cyanColor];
    [cell.field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];

    int price = 0;
    for (int i =0; i<priceArr.count; i++) {
        
        price = price+[priceArr[i] intValue];
    }
    NSString * stringPrice = [NSString stringWithFormat:@"¥ %d 元",price];
    cell.price.text = stringPrice;
    return cell;
    
}
-(void)pressBtn2:(UIButton*)sender{
    
    
    
    
    
}

-(void)textFieldWithText:(UITextField*)field{
    
    UITableViewCell *cell = (UITableViewCell*)[[field superview] superview];
    NSIndexPath *indexPath = [table indexPathForCell:cell];
    [priceArr replaceObjectAtIndex:indexPath.section withObject:field.text];
    
    //一个cell刷新
    NSIndexPath * NewindexPath=[NSIndexPath indexPathForRow:0 inSection:3];
    [table reloadRowsAtIndexPaths:[NSArray arrayWithObjects:NewindexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 37*kHeight;
    
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    
    return dataSouceArr[section][@"feeType"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [dataSouceArr[section][@"list"] count];
}
//设置分区个数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [dataSouceArr count];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        

    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

//-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    　　NSMutableString *text = [[moneyInputField.text mutableCopy] autorelease];
//    　　[text replaceCharactersInRange:range withString:string];
//    　　return [text length] <= 12;
//    　　}

//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    
//
//    
//　　NSMutableString * text = [textField.text mutableCopy];
//　　[text replaceCharactersInRange:range withString:string];
//　　return [text length] <= 12;
//    
//}

-(CustomTextField*)createField:(NSString*)placeholder andTag:(NSInteger)tag andFont:(double)font{
    
    CustomTextField * field =[[CustomTextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-90*kWidth, 43*kWidth);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentCenter;
    CGFloat width = field.frame.size.width;
    CGFloat height = field.frame.size.height;
    //控制placeHolder的位置
    [field placeholderRectForBounds:CGRectMake(width/2, 0, width, height)];
    [field editingRectForBounds:CGRectMake(width/2, 0, width, height)];
    [field leftViewRectForBounds:CGRectMake(width/2, 0, width, height)];
    [field textRectForBounds:CGRectMake(width/2, 0, width, height)];

    return field;
}

@end
